package com.example.demo1.controller;

import com.example.demo1.Person;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@RequestMapping("/return")

@Controller
//Controller 返回视图
//RestController 返回数据 可以修饰类 也可以修饰方法
public class ReturnController {
    //返回html
    @RequestMapping("/index")
    public String returnIndex(){
        return "/index.html";
    }

    //返回视图所需要的数据
    @ResponseBody
    //RestController = ResponseBody + Controller
    @RequestMapping("/returnData")
    public String returnData(){
        return "返回视图所需要的数据";
    }

    //返回HTML代码片段
    @ResponseBody
    @RequestMapping("/returnHtml")
    public String returnHtml(){
        return "<h1>返回html片段<h1>";
    }

    //返回json
    //当我们的接口返回的是String时 content-type是text/html
    //当我们的接口返回的是对象和map时,content-type自动设置为application/json
    @ResponseBody
    @RequestMapping("/returnJson")
    public Person returnJson(){
        Person person = new Person();
        person.setId(1);
        person.setAge(18);
        person.setName("zhangsan");
        return person;
    }

    @ResponseBody
    @RequestMapping("/returnMap")
    public Map<Map<String,String>,String> returnMap(){
        Map<Map<String,String>,String> map = new HashMap<>();
        Map<String,String> kv1 = new HashMap<>();
        kv1.put("k1","v1");
        Map<String,String> kv2 = new HashMap<>();
        kv2.put("k2","v2");
        Map<String,String> kv3 = new HashMap<>();
        kv3.put("k3","v3");
        map.put(kv1,"1");
        map.put(kv2,"2");
        map.put(kv3,"3");
        return map;
    }

    //设置状态码
    @ResponseBody
    @RequestMapping("/setStatus")
    public String setStatus(HttpServletResponse response){
        response.setStatus(401);
        return "设置状态码";
    }

    //设置body
    @ResponseBody
    @RequestMapping(value = "/r1" , produces = "application/json;charset=utf-8")
    public String r1(HttpServletResponse response){
        //设置header
        response.setHeader("myhead","myhead");
        return "{'OK' : 1}";
    }
}
